package cn.yunyichina.provider.register.service.impl;

import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterDeptsVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterDeptsVoResponse;
import cn.yunyichina.provider.register.constant.CacheConstant;
import cn.yunyichina.provider.register.utils.RegUtil;
import cn.yunyichina.provider.register.vo.RegisterDeptsVoOut;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by Administrator on 2016/12/1.
 */
@Service
public class RegDeptServiceImpl {


    /**
     * 1天共计的秒数
     */
    public static final int DAY_SECONDS = 24*60*60;

    private Logger logger = LoggerFactory.getLogger(RegDeptServiceImpl.class);

    /**
     * 可挂号科室 yyt.register.dept.list --> yyt.register.reg.dept.list
     * @param data
     * @param sessionId
     * @return
     */
    public Response listRegDept(String data, String sessionId) {
        logger.info("listRegDept, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();

        RegisterDeptsVo deptsVo = JsonUtils.parseObject(data, RegisterDeptsVo.class);

        String cacheKey = deptsVo.getHospitalCode() + (StringUtils.isNotBlank(deptsVo.getBranchCode())?":" + deptsVo.getBranchCode() : "");
        String cacheValue = CacheService.getGlobalKey(CacheConstant.CACHE_REGISTER_MODULE,CacheConstant.CACHE_REGISTER_DEPT,cacheKey);
        if(StringUtils.isBlank(cacheValue)){
            //缓存为空，更新缓存并返回科室数据
            return updateRegDeptCache(data,sessionId);
        }
//        logger.info("listDept, cache hit value=" + cacheValue);

        List<RegisterDeptsVoOut> deptsVoResponses = JsonUtils.parseObject(cacheValue, List.class);
        if (CollectionUtils.isEmpty(deptsVoResponses)) {
            response.setResultCodeAndMessage("6002", "不存在可挂号科室！");
            return response;
        } else {
            response.setResult(JsonUtils.toJsonString(deptsVoResponses));
        }
        return response;
    }

    /**
     * 可挂号科室缓存 yyt.register.dept.cache.update --> yyt.register.reg.dept.cache.update
     * @param data
     * @param sessionId
     * @return
     */
    public Response updateRegDeptCache(String data, String sessionId) {
        logger.info("updateRegDeptCache, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();

        RegisterDeptsVo deptsVo = JsonUtils.parseObject(data, RegisterDeptsVo.class);

        ResCommon<List<RegisterDeptsVoResponse>> deptsResponse = HisifaceService.getHisifaceClient().getRegisterDepts(deptsVo);
        logger.info("updateRegDeptCache, call hisiface getRegisterDepts request={},response={}",
                JSONObject.toJSONString(deptsVo),JSONObject.toJSONString(deptsResponse));
        if (!ResCommon.SUCCESS_CODE.equals(deptsResponse.getResultCode())) {
            response.setResultCodeAndMessage("6000",
                    "查询可挂号科室失败，医院编码：" + deptsVo.getHospitalCode() + "！");
            return response;
        }

        List<Map<String,Object>> deptsVoResponses = JsonUtils.parseObject(deptsResponse.getResult(), List.class);

        if (CollectionUtils.isEmpty(deptsVoResponses)) {
            response.setResultCodeAndMessage("6002", "不存在可挂号科室！");
            return response;
        } else {
            List<RegisterDeptsVoOut> outList = new ArrayList<>();
            //预约挂号日期显示天数
            String calendarDays  = RegUtil.getRule(deptsVo.getHospitalCode(),RegUtil.CALENDAR_DAYS_TYPE,"7");
            for(Map map:deptsVoResponses){
                //转换为规范输出
                RegisterDeptsVoOut dept = new RegisterDeptsVoOut();
                dept.setDeptCode((String)map.get("dept_code"));
                dept.setDeptName((String)map.get("dept_name"));
                dept.setDeptTelephone((String)map.get("dept_telephone"));
                dept.setDeptDescription((String)map.get("dept_description"));
                dept.setParentDeptCode((String)map.get("parent_dept_code"));
                dept.setDeptAddress((String) map.get("dept_location"));
                dept.setInsuranceFlag((String) map.get("insurance_flag"));
                if(StringUtils.isNotBlank(calendarDays)) {
                    dept.setCalendarDays(Integer.parseInt(calendarDays));
                }
                outList.add(dept);
            }

            String cacheKey = deptsVo.getHospitalCode() + (StringUtils.isNotBlank(deptsVo.getBranchCode())?":" + deptsVo.getBranchCode() : "");
            Response cacheResponse = CacheService.setGlobalKey(CacheConstant.CACHE_REGISTER_MODULE,CacheConstant.CACHE_REGISTER_DEPT,cacheKey,JsonUtils.toJsonString(outList),DAY_SECONDS);
            if("0".equals(cacheResponse.getResultCode())) {
                response.setResult(JsonUtils.toJsonString(outList));
            }else {
                response.setResultCodeAndMessage(cacheResponse.getResultCode(),cacheResponse.getResultMessage());
            }
        }
        return response;
    }

}
